package com.tanklab.signature.config;

import com.tanklab.signature.common.util.JwtUtils;
import com.tanklab.signature.common.util.ResultCode;
import com.tanklab.signature.common.util.TokenBlacklistManager;
import com.tanklab.signature.ds.resp.CommonResp;
import org.springframework.beans.factory.annotation.Autowired;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Service
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private TokenBlacklistManager blacklistManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        System.out.println("JWT拦截器被调用");
        // 放行登录、刷新Token接口和登出接口
        String requestURI = request.getRequestURI();
        if (requestURI.endsWith("/auth/login") || requestURI.endsWith("/auth/refresh-token") || requestURI.endsWith("/auth/logout")) {
            return true;
        }

        // 检查Token是否存在
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            returnJson(response, ResultCode.TOKEN_MISS, "Token不存在");
            return false;
        }

        // 如果以Bearer开头，移除这个前缀
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        // 检查Token是否在黑名单中
//        if (blacklistManager.isBlacklisted(token)) {
//            returnJson(response, ResultCode.TOKEN_INVALID, "Token已被注销");
//            return false;
//        }

        // 验证Token有效性
        if (!jwtUtils.validateToken(token)) {
            returnJson(response, ResultCode.TOKEN_INVALID, "Token无效或已过期");
            return false;
        }

        // Token即将过期，在响应头中添加标记
        if (jwtUtils.isTokenNearExpiration(token)) {
            response.setHeader("X-Token-Expire-Soon", "true");
        }

        // 通过验证
        return true;
    }

    // 返回JSON错误消息
    private void returnJson(HttpServletResponse response, ResultCode code, String message) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        CommonResp<Object> resp = new CommonResp<>();
        resp.setRet(code);
        resp.setMsg(message);

        response.getWriter().write(objectMapper.writeValueAsString(resp));
    }
}


